package com.shine.sys.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shine.common.repository.hibernate.HibernateDao;
import com.shine.common.service.BaseServiceImpl;
import com.shine.common.web.model.DataTables;
import com.shine.common.web.model.Page;
import com.shine.common.web.model.SystemContext;
import com.shine.sys.entity.Role;
import com.shine.sys.service.RoleService;


@Service
public class RoleServiceImpl extends BaseServiceImpl<Role, Integer> implements RoleService {
	
	@Autowired
	private HibernateDao<Role, Integer> basedaoRole ;

	@Override
	public void delete(String ids) {
		if(null != ids && ids.length() > 0) {
			String[] split = ids.split(",") ;
			for (String id : split) {
				super.delete(Integer.parseInt(id));
			}
		}
	}
	
	@Override
	public DataTables datatables(Role entity) {
		Page<Role> findByPage = this.findByPage(entity) ;
		return new DataTables(SystemContext.getDraw(), findByPage.getTotalNumber(), findByPage.getTotalNumber(), findByPage.getDataRows(), SystemContext.getPageNumber(), SystemContext.getCurrentPage()) ;
	}

	@Override
	public Page<Role> findByPage(Role entity) {
		StringBuffer queryString = new StringBuffer("SELECT t.* FROM sys_role t WHERE 1=1") ;
		
		Map<String, Object> alias = new HashMap<String, Object>() ;
		queryString = addWhere(queryString, alias, entity) ;
		
		return this.basedaoRole.findPageSQL(queryString.toString(), alias, Role.class, false) ;
	}

	private StringBuffer addWhere(StringBuffer queryString, Map<String, Object> alias, Role entity) {
		if(null != entity) {
			if(null != entity.getId()) {
				queryString.append(" AND t.id=:id") ;
				alias.put("id", entity.getId()) ;
			}
			if(entity.getQuickSearch() != null && !"".equals(entity.getQuickSearch())){
				queryString.append(" and ")
				.append("(")
				.append("t.name like '%%" + entity.getQuickSearch() + "%%'")
				.append(" or t.description like '%%" + entity.getQuickSearch() + "%%'")
				.append(")");
			}
		}
		return queryString;
	}
	
}
